package csu.big_article.exception;

import csu.big_article.msg.ResponseCode;
import csu.big_article.pojo.CommonResponse;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public CommonResponse<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error(e.getMessage());
        return CommonResponse.createForError(ResponseCode.UserRegisterMissingParam.getCode(),ResponseCode.UserRegisterMissingParam.getDescription());
    }


    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public CommonResponse<String> handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage());
        return CommonResponse.createForError(ResponseCode.UserNameOrPasswordNotNull.getCode(),ResponseCode.UserNameOrPasswordNotNull.getDescription());
    }

    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public CommonResponse<String> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        logger.error(e.getMessage());
        return CommonResponse.createForError(ResponseCode.UserNameDuplicate.getCode(),ResponseCode.UserNameDuplicate.getDescription() );
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public CommonResponse<String> handleException(Exception e) {
        logger.error(e.getMessage());
        return CommonResponse.createForError();
    }
}
